package com.lx.oms.controller.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lx.oms.common.annotation.SysLog;
import com.lx.oms.common.controller.AbstractController;
import com.lx.oms.common.entity.Page;
import com.lx.oms.common.entity.R;
import com.lx.oms.common.utils.ImageOperation;
import com.lx.oms.common.utils.excel.ExcelsUtils;
import com.lx.oms.controller.entity.FactoryEntity;
import com.lx.oms.controller.entity.QuotationPriceEntity;
import com.lx.oms.controller.entity.SysCategoryEntity;
import com.lx.oms.controller.service.FactoryService;
import com.lx.oms.controller.service.QuotationPriceService;
import com.lx.oms.controller.service.SysCategoryService;

/**
 * 行情价格
 *
 * @author houzhong
 * @date 2018年7月12日 下午2:41:51
 */
@RestController
@RequestMapping("/sys/quotationprice")
public class QuotationPriceController extends AbstractController {
	
	@Autowired
	private QuotationPriceService quotationPriceService;
	
	/**
	 * 厂名
	 */
	@Autowired
	private FactoryService factoryService;
	
	/**
	 * 分类
	 */
	@Autowired
	private SysCategoryService sysCategoryService;
	
	/**
	 * 列表
	 * @param params
	 * @return
	 */
	@RequestMapping("/list")
	public Page<QuotationPriceEntity> list(@RequestBody Map<String, Object> params) {
		return quotationPriceService.listQuotationPrice(params);
	}
		
	/**
	 * 新增
	 * @param tQuotationPrice
	 * @return
	 */
	@SysLog("新增行情价格")
	@RequestMapping("/save")
	public R save(@RequestBody QuotationPriceEntity quotationprice) {
		quotationprice.setCreateTime(new Date());
		return quotationPriceService.saveQuotationPrice(quotationprice);
	}
	
	/**
	 * 根据id查询详情
	 * @param id
	 * @return
	 */
	@RequestMapping("/info")
	public R getById(@RequestBody String id) {
		return quotationPriceService.getQuotationPriceById(new BigInteger(id));
	}
	
	/**
	 * 修改
	 * @param tQuotationPrice
	 * @return
	 */
	//@SysLog("修改行情价格")
	@RequestMapping("/update")
	public R update(@RequestBody QuotationPriceEntity quotationPrice) {
		return quotationPriceService.updateQuotationPrice(quotationPrice);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@SysLog("删除行情价格")
	@RequestMapping("/remove")
	public R batchRemove(@RequestBody String[] id) {
		return quotationPriceService.batchRemove(id);
	}
	
	/**
	 * EXCEL导入
	 */
	@RequestMapping("upload")
	public void excelPeopleNumber(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				String name = item.getName();
				name = name.substring(name.lastIndexOf("\\") + 1);
				String url = request.getSession().getServletContext().getRealPath("/") + ("/fileImage/");
				//目录不存在创建
				ImageOperation.createFolder(url);
				// 获取item中的上传文件的输入流
				InputStream in = item.getInputStream();
				// 创建一个文件输出流
				FileOutputStream out = new FileOutputStream(url + name);
				// 创建一个缓冲区
				byte bf[] = new byte[1024];
				// 判断输入流中的数据是否已经读完的标识
				int len = 0;
				// 循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
				while ((len = in.read(bf)) > 0) {
					// 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
					out.write(bf, 0, len);
				}
				out.close();
				in.close();
				
				List<QuotationPriceEntity> entList = new ArrayList<QuotationPriceEntity>();
				List<List<String>> list = ExcelsUtils.readFile(url + name);
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {

						if (0 == i) {
							continue;
						}
						// 获取每行数据
						List<String> cellList = list.get(i);

						QuotationPriceEntity entity = new QuotationPriceEntity();
						entity.setProvince(cellList.get(0));
						// 一级分类
						SysCategoryEntity categoryEntity = sysCategoryService.getCategoryByName(cellList.get(1));
						if (categoryEntity != null) {
							entity.setCategoryId(categoryEntity.getCategoryId());
						}
						//二级分类
						categoryEntity = sysCategoryService.getCategoryByName(cellList.get(2));
						if (categoryEntity != null) {
							entity.setCategoryTwo(categoryEntity.getCategoryId());
						}
						if (!"".equals(cellList.get(3))) {
							//三级分类
							categoryEntity = sysCategoryService.getCategoryByName(cellList.get(3));
							if (categoryEntity != null) {
								entity.setCategoryThree(categoryEntity.getCategoryId());
							}
						}
						
						//根据名称查询厂名是否存在
						FactoryEntity factoryEntity = factoryService.getFactoryByName(cellList.get(4));
						if (factoryEntity != null) {
							//厂名id
							entity.setFactoryId(factoryEntity.getId());
						}
						// 时间
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time = cellList.get(5) + " 00:00:00";
						Date date = df.parse(time);
						entity.setCreateTime(date);
						//价格
						entity.setPrice(cellList.get(6));
						
						entity.setActive(1);

						// 放入集合
						entList.add(entity);
					}
					
					// 统一保存
					for (QuotationPriceEntity entity : entList) {
						quotationPriceService.saveQuotationPrice(entity);
					}
					//删除缓存文件
					ImageOperation.deleteFile(url + name);
				}
			}
		}
		response.sendRedirect(request.getContextPath() + "/base/quotationprice/list.html");
	}
	
}
